package com.example.chatserver;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class TcpNioClient implements Runnable{
	private Selector selector = null;
	private SocketChannel socket = null;
	InetSocketAddress ipp = null;
	private byte[] stream;

	public TcpNioClient(String ip, int port) throws Exception {
		selector = Selector.open();
		socket = SocketChannel.open();
		socket.configureBlocking(false);
		socket.register(selector, SelectionKey.OP_CONNECT);
		ipp = new InetSocketAddress(ip, port);
		socket.connect(ipp);
	}
	//PAD�ͻ���,ֱ�ӷ���
	public TcpNioClient(String ip,int port,byte[] stream) throws Exception{
		this.stream = stream;
		selector = Selector.open();
		socket = SocketChannel.open();
		socket.configureBlocking(false);
		socket.register(selector, SelectionKey.OP_CONNECT);
		ipp = new InetSocketAddress(ip, port);
		socket.connect(ipp);
		send(stream);
	}
	//��������ת�ͻ��ˣ������̷߳�����Ϣ
	public TcpNioClient(byte[] stream,String ip,int port) throws Exception{
		this.stream = stream;
		selector = Selector.open();
		socket = SocketChannel.open();
		socket.configureBlocking(false);
		socket.register(selector, SelectionKey.OP_CONNECT);
		ipp = new InetSocketAddress(ip, port);
		socket.connect(ipp);
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		this.send(stream);
	}
	
	public void send(String message) {
		if (message != null)
			try {
				this.send(message.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
	}

	public void send(byte[] message) {
		try {

			boolean isSent = false;
			while (true) {
				if (isSent)
					break;
				int selectValue = selector.select(1000);
				if (selectValue == 0)
					break;
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();
				while (it.hasNext()) {
					SelectionKey key = it.next();
					it.remove();
					if (key.isConnectable()) {
						SocketChannel channel = (SocketChannel) key.channel();
						channel.configureBlocking(false);

						if (channel.isConnectionPending()) {
							System.out.println("connection is pending");
							channel.finishConnect();
						}
						channel.register(selector, SelectionKey.OP_WRITE);
					} else if (key.isWritable()) {
						SocketChannel channel = (SocketChannel) key.channel();
						if (channel.isConnected())
							channel.write(ByteBuffer.wrap(message));
						isSent = true;
						channel.socket().close();
					} else if (key.isReadable()) {

					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


